package tgc.edu.fhh.web.controller;



import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import tgc.edu.fhh.custom.AjaxResult;
import tgc.edu.fhh.entity.MenuDto;
import tgc.edu.fhh.entity.SysDept;
import tgc.edu.fhh.service.SysDeptService;
import tgc.edu.fhh.web.form.SysDeptForm;

@RestController
@CrossOrigin
@RequestMapping(value = "SysDept")
public class SysDeptController {
	
	

	@Autowired
	private SysDeptService sysDeptService;

	@RequestMapping(value = "/list")
	public Object findAll() {
		List<SysDept> list = sysDeptService.findAll();
		List<MenuDto> dtoTreeList = getDtoTreeList(list);
		return new AjaxResult(true, "数据来了", dtoTreeList);
	}
	@RequestMapping(value = "/save")
	public Object save(SysDeptForm form) {
		try {
			SysDept sysDept=new SysDept();
			if(form.getId()!=null) {
				sysDept=sysDeptService.findById(form.getId());
			}
			BeanUtils.copyProperties(form, sysDept,"id","children");
			if(form.getParentId()!=0) {
				sysDept.setParent(sysDeptService.findById(form.getParentId()));
			}else {
				sysDept.setParent(null);
			}
			sysDeptService.save(sysDept);
			return new AjaxResult(true, "保存成功!", "");
		} catch (Exception e) {
			return new AjaxResult(false, "保存失败，请稍后再试!", "");
		}
		
	}
	@RequestMapping(value = "del")
	public Object del(Integer id) {
		try {
			sysDeptService.deleteById(id);
			return new AjaxResult(true, "删除成功", ""); 
		} catch (Exception  e) {
			// TODO: handle exception
			return new AjaxResult(false, "删除失败，请稍后再试！", "");
		}
	}

	public List<MenuDto> getDtoTreeList(List<SysDept> list) {
		List<MenuDto> dtos = new ArrayList<>();
		if (list == null || list.isEmpty()) {
			return dtos;
		}
		for (SysDept menu : list) {
			if (menu.getParentId() == null) {
				MenuDto menuDto = new MenuDto();
				BeanUtils.copyProperties(menu, menuDto, "children");
				MenuDto findChildren = findChildren(menuDto, list);
				dtos.add(findChildren);
			};
		}
		return dtos;
	}

	private MenuDto findChildren(MenuDto menuDto, List<SysDept> list) {
		for (SysDept menu : list) {
			if (menuDto.getId().equals(menu.getParentId())) {
				// 此时menu是menuDto下的子级
				if (menuDto.getChildren() == null) {
					menuDto.setChildren(new ArrayList<MenuDto>());
				}
				MenuDto dto = new MenuDto();
				BeanUtils.copyProperties(menu, dto, "children");
				// 递归
				menuDto.getChildren().add(findChildren(dto, list));
			}
		}
		return menuDto;
	}

}
